﻿using System.Collections;
using System.Collections.Generic;
using Utility;

namespace Utility.TaskSystem
{
	public struct TaskEventContext
	{
		public Task task;
		public bool isAbort;
	}

	public class TaskEvent : UnityEngine.Events.UnityEvent<TaskEventContext> { }

	public class Task
	{
		public bool Active { get; set; } = true;
		public bool Alive { get; protected set; } = true;
		public int Frames { get; protected set; } = 0;

		TaskEvent e_onDone;
		public TaskEvent E_OnDone
		{
			get
			{
				if (e_onDone == null)
				{
					e_onDone = new TaskEvent ();
				}
				return e_onDone;
			}
		}

		/// <summary>
		/// return true for successful update
		/// </summary>
		/// <returns></returns>
		public bool Update ()
		{
			if (Alive)
			{
				if (Active)
				{
					Frames++;
					OnUpdate ();
					return true;
				}
			}
			return false;
		}

		protected virtual void OnUpdate ()
		{
		}

		protected void Done (bool isAbort = false)
		{
			if (Alive)
			{
				Alive = false;
				if (e_onDone != null)
				{
					TaskEventContext context = new TaskEventContext ();
					context.task = this;
					context.isAbort = isAbort;
					e_onDone.Invoke (context);
				}
			}
		}
	}
}